const queryString = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const utils = require('./src/utils/handlePostData');
const serverHandle = (req, res) => {
  // 设置返回的格式
  res.setHeader('Content-Type', 'application/json')

  // 解析url
  const { url } = req

  // 解析path
  const path = url.split('?')[0]

  // 处理body
  utils.getPostData(req).then(postData => {
    req.body = postData
    
    // 处理query
    req.query = queryString.parse(url.split('?')[1])
    
    // 处理blog路由
    const blogData = handleBlogRouter(req, res)
    if (blogData) {
      blogData.then(blogData => res.end(JSON.stringify(blogData)))
      return
    }
    
    // 处理user路由
    const userData = handleUserRouter(req, res)
    if (userData) {
      userData.then(result => res.end(JSON.stringify(result)))
      return
    }
  
    // 未命中则返回404
    res.writeHead('Content-Type', 'text/plain')
    res.write('404 Not Found\n')
    res.end()
  })
}
module.exports = serverHandle